const md5 = require('md5')
const dataBase = require('../../mysql')
const jwt = require('jsonwebtoken')
const key = require('../../auth/key')

const sql = require('../../mysql/sql')
const verifyRequestMethod = require('../../tool/verifyRequestMethod')

/**
 * @description 登录
 */
module.exports = function () {
    const that = this
    /**
     * @description 获取query
     * @type {{}|*}
     */
    const query = this.getQueryData(this.request.url)
    /**
     * @description 请求验证
     */
    verifyRequestMethod(this.request, 'GET').then(function () {
        /**
         * @description 表单验证
         */
        if (!query.username || !/^[1-9]\d{7,10}$/.test(query.username)) {
            that.response.outPrintError('请输入正确的账号！')
        } else if (!query.password || !/^(?=.*\d)(?=.*[a-zA-Z]).{6,20}$/.test(query.password)) {
            that.response.outPrintError('请输入正确的密码！')
        } else {
            return dataBase.connect(sql.SQL_QUERY_USER(query.username, md5(query.password)))
        }
    }).then(function (result) {
        /**
         * @description 处理返回值
         */
        if (result[0] !== undefined) {
            const token = jwt.sign({
                username: query.username,
                password: query.password,
                type: result[0].type
            }, key, {
                expiresIn: 60 * 60 * 3
            })
            that.response.outPrintData({ token: token }, '登录成功！')
        } else {
            that.response.outPrintError('登录失败，请检查密码或账号是否正确！')
        }
    }).catch(function (e) {
        that.response.outPrintError((e && e.message) || '未知错误！')
    })
}